package org.jw.wishlist.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * @author Jiawei Zhao
 */
public final class ApplicationContextUtils {

  private static ApplicationContext context;

  private ApplicationContextUtils() {
  }

  public static void setApplicationContext(ApplicationContext context) {
    Assert.notNull(context, "ApplicationContext 不能为空");
    ApplicationContextUtils.context = context;
  }

  @Nullable
  public static <T> T getBean(Class<T> beanType) {
    try {
      return getRequiredBean(beanType);
    } catch (BeansException e) {
      return null;
    }
  }

  public static <T> T getRequiredBean(Class<T> beanType) throws BeansException {
    return context.getBean(beanType);
  }

  public static <T> T getRequiredBean(String beanName, Class<T> beanType) throws BeansException {
    return context.getBean(beanName, beanType);
  }

}
